<script setup lang="ts">
import { ref } from "vue"
import { $t } from '#/locales'
import { ElMessage } from "element-plus";
import { createSysOrgApi, updateSysOrgApi, getSysOrgTreeApi } from '#/api/system/systemOrg';

defineOptions({ name: 'Dialog' })
const inputNTxt = $t('common.inputPhTxt', [$t('orgMgr.orgNameTxt')])
const bindCertTxt = $t('common.selectPhTxt', [$t('orgMgr.parOrgTxt')])

defineProps({

});

const titleTxt = {
  sublevel: $t('common.newTxt'),
  plevel: $t('common.newTxt'),
  edit: $t('common.editTxt'),
}

const emit = defineEmits(['queryTable'])
const submitLoading = ref(false)
const dialogVisible = ref(false)
const formRef = ref()
const defaultFormInline = {
  name: null,
  pid: null
}
const formInline = ref({ ...defaultFormInline })
const editData = ref<any>(null)
const handleType = ref<any>('PLEVEL')
const listData = ref<any>([])
const rules = {
  name: [
    { required: true, message: inputNTxt, trigger: 'blur' },
  ],
  pid: [
    { required: true, message: bindCertTxt, trigger: 'change' },
  ]
}

const handleClose = () => {
  formInline.value = { ...defaultFormInline }
  formRef.value.resetFields()
  dialogVisible.value = false
}
const inint = (type: any, data: any) => {
  editData.value = data ?? null
  handleType.value = type.toLowerCase()
  if (type === 'EDIT') {
    const { name, pid } = data
    formInline.value = { name, pid: pid }
  }
  if (type === 'SUBLEVEL') {
    const { id } = data
    formInline.value = { name: null, pid: id }
  }
  dialogVisible.value = true
  getTabelData()
}
const setOrgDisabled = (data: any) => {
  return data.filter((item: any) => {
    // 过滤掉当前编辑的节点
    if (item.id === editData.value.id) {
      return false
    }
    // 递归处理 children
    if (item.children && item.children.length > 0) {
      item.children = setOrgDisabled(item.children)
    }
    return true
  })
}
const getSubLevelData = (data: any) => {
  const findNodeById = (nodes: any[], targetId: any): any[] => {
    for (const node of nodes) {
      if (node.id === targetId) {
        return [node]
      }
      if (node.children && node.children.length > 0) {
        const found = findNodeById(node.children, targetId)
        if (found.length > 0) {
          return found
        }
      }
    }
    return []
  }
  
  return findNodeById(data, editData.value.id)
}
const getTabelData = () => {
  const params = {
    curPage: 1,
  } as any;
  getSysOrgTreeApi(params)
    .then((res) => {
      const { data } = res;
      listData.value = data
      if (editData.value) {
        listData.value = handleType.value === 'sublevel' ? getSubLevelData(data) : setOrgDisabled(data)
      } else {
        listData.value = data
      }
    })
    console.log(listData.value)
};

const submit = () => {
  if (!formRef) return
  formRef.value?.validate((valid: any) => {
    if (valid) {
      let params = {
        name: formInline.value.name,
        pid: formInline.value.pid
      } as any

      if (handleType.value === 'edit') {
        params['id'] = editData.value.id
      }
      submitLoading.value = true
      const Api = handleType.value === 'edit' ? updateSysOrgApi(params) : createSysOrgApi(params)
      Api.then(() => {
        ElMessage.success($t('common.handleTxt', [$t('common.successTxt')]))
        emit('queryTable')
        handleClose()
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

defineExpose({ inint })

</script>
<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :title="titleTxt[handleType as keyof typeof titleTxt]"
    width="500" :append-to-body="true" :close-on-click-modal="false" :before-close="handleClose">
    <el-form ref="formRef" :model="formInline" :rules="rules" label-width="80px">
      <el-form-item :label="$t('orgMgr.orgNameTxt')" prop="name">
        <el-input v-model="formInline.name" clearable :maxlength="50" :placeholder="inputNTxt" />
      </el-form-item>
      <el-form-item :label="$t('orgMgr.parOrgTxt')">
        <el-cascader clearable :show-all-levels="false" class="w-full" v-model="formInline.pid" :placeholder="bindCertTxt" :options="listData" :props="{emitPath: false, checkStrictly: true, multiple: false, label: 'name', value: 'id', children: 'children'}" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="handleClose">
          {{ $t('common.cancelTxt') }}
        </el-button>
        <el-button type="primary" @click="submit" :loading="submitLoading">
          {{ $t('common.submitTxt') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
